package com.taotao.rest.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.taotao.mapper.TbItemCatMapper;
import com.taotao.pojo.TbItemCat;
import com.taotao.pojo.TbItemCatExample;
import com.taotao.pojo.TbItemCatExample.Criteria;
import com.taotao.rest.dao.JedisClient;
import com.taotao.rest.pojo.CatNode;
import com.taotao.utils.JsonUtils;
@Component
public class ItemCatServiceImpl implements ItemCatService {
	@Autowired
	private TbItemCatMapper itemCatMapper;
	@Autowired
	private JedisClient jedisClient;
	
	@Value("${INDEX_ITEMCAT_REDIS_KEY}")
	private String INDEX_ITEMCAT_REDIS_KEY;
	@Override
	public List<?> getItemCat(long parentId) {
		
		
		try {
			String result = jedisClient.hget(INDEX_ITEMCAT_REDIS_KEY, parentId +"");
			if (result == "" || result == null) {
				throw new Exception("缓存中没有");
			}
			List<Object> jsonToList = JsonUtils.jsonToList(result, Object.class );
			return jsonToList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		
		List<?> catList = getCatList(parentId);
		
		
		try {
			jedisClient.hset(INDEX_ITEMCAT_REDIS_KEY, parentId+"", JsonUtils.objectToJson(catList));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return catList;
	}
	
	private List<?> getCatList(long parentId) {
		TbItemCatExample example = new TbItemCatExample();
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		List<TbItemCat> list = itemCatMapper.selectByExample(example);
		List nodeList = new ArrayList();
		// 如果是父节点就继续查找
		for (TbItemCat itemCat : list) {
			CatNode node = new CatNode();
			if (itemCat.getIsParent()) {
				if (itemCat.getParentId() == 0) {
					node.setName("<a href='/products/" + itemCat.getId()+ ".html'>"+itemCat.getName()+"</a>");
				} else {
					node.setName(itemCat.getName());
				}
				node.setUrl("/products/"+itemCat.getId()+".html");
				node.setItem(getCatList(itemCat.getId()));
				nodeList.add(node);
			} else {
				nodeList.add("/products/"+itemCat.getId()+".html|" +itemCat.getName());
			}

		}
		return nodeList;
	}

}
